// pages/me/changePwd/changePwd.js
import * as API from '../../../api/loginApi';
import * as myApi from '../../../api/myApi';
import * as util from '../../../utils/util';

let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    btnText: '获取验证码',
    phone: '',
    vCode: '',
    isSendClass: '',
    showKeyboad: false,
    editPassword: false
  },

  bindKeyInput: function (e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      [name]: e.detail.value
    });
  },

  //发送验证码
  sendCode() {
    if (this.data.isSend) return;
    wx.showLoading({ title: '验证码发送中', })
    API.sendVCode(this.data.phone).then(data => {
      countDown(this, 60);
      wx.hideLoading();
      util.toast('验证码发送成功');
    }, err => {
      wx.hideLoading();
      util.toast(err);
    });
  },

  //下一步提交表单
  formSubmit() {
    //校验输入是否有效
    util.preventMoreClick(this, () => {
      var valid = validateCode(this);
      if (!valid) return;
      wx.showLoading({})
      API.findPasswordNextStep(this.data.phone, this.data.vCode).then(data => {
        wx.hideLoading();
        wx.navigateTo({
          url: './changePwd2?phone=' + this.data.phone + '&authorizationCode=' + data.authorizationCode,
        });
      }, err => {
        wx.hideLoading();
        util.toast(err || '失败，请稍后再试');
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let user = wx.getStorageSync('user');
    if (user) {
      this.setData({
        phone: user.phone || ''
      });
    } else {
      myApi.getUserInfo().then(res => {
        this.setData({
          phone: res.user && res.user.phone,
        });
      }, err => {
        util.toast('获取用户信息失败');
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
});

//验证码
function countDown(that, count) {
  if (count <= 0) {
    that.setData({
      btnText: '获取验证码',
      isSendClass: '',
      isSend: false
    })
    return;
  }

  that.setData({
    isSend: true,
    isSendClass: 'isSendClass',
    btnText: '已发送' + count + 'S',
  })

  setTimeout(function () {
    count--;
    countDown(that, count);
  }, 1000);
}

function validateCode(that) {
  var value = that.data.vCode;
  if (!value || value.length != 4) {
    util.toast('验证码错误');
    return false;
  }
  return true;
}